import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getAuth } from '@/api/auth/auth'
import type { RegisterRequest, LoginRequest } from '@/api/models'

export interface User {
  id: string
  username: string
  email: string
  full_name: string
  family_name: string
  token: string
  role?: string
}

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  const isInitialized = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value && isInitialized.value)
  const userRole = computed(() => user.value?.role || 'guest')

  // 方法
  const setAuth = (userData: User, userToken: string) => {
    user.value = userData
    token.value = userToken
    localStorage.setItem('token', userToken)
    error.value = null
  }

  const clearAuth = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
    error.value = null
  }

  const setLoading = (loading: boolean) => {
    isLoading.value = loading
  }

  const setError = (errorMessage: string) => {
    error.value = errorMessage
  }

  const clearError = () => {
    error.value = null
  }

  // 验证token并恢复用户信息
  const verifyToken = async () => {
    if (!token.value) {
      isInitialized.value = true
      return false
    }

    try {
      setLoading(true)
      const { verifyTokenEndpointApiV1AuthVerifyTokenPost } = getAuth()
      const response = await verifyTokenEndpointApiV1AuthVerifyTokenPost()
      
      // 根据token验证响应恢复用户信息
      const userData: User = {
        id: response.id.toString(),
        username: response.username,
        email: response.email,
        full_name: response.full_name,
        family_name: response.family_name || '',
        token: token.value,
        role: response.role
      }
      
      user.value = userData
      isInitialized.value = true
      return true
    } catch (error) {
      console.error('Token验证失败:', error)
      // token无效，清除本地存储
      clearAuth()
      isInitialized.value = true
      return false
    } finally {
      setLoading(false)
    }
  }

  // 初始化认证状态
  const initializeAuth = async () => {
    if (isInitialized.value) return
    
    if (token.value && !user.value) {
      await verifyToken()
    } else {
      isInitialized.value = true
    }
  }

  // 注册方法
  const register = async (registerData: RegisterRequest) => {
    try {
      setLoading(true)
      clearError()
      
      const { registerApiV1AuthRegisterPost } = getAuth()
      await registerApiV1AuthRegisterPost(registerData)
      
      // 注册成功后自动登录
      const loginData: LoginRequest = {
        username: registerData.username,
        password: registerData.password
      }
      
      const { loginApiV1AuthLoginPost } = getAuth()
      const loginResponse = await loginApiV1AuthLoginPost(loginData)
      
      // 设置用户信息
      const userData: User = {
        id: loginResponse.family_member.id.toString(),
        username: loginResponse.family_member.username,
        email: loginResponse.family_member.email,
        full_name: loginResponse.family_member.full_name,
        family_name: loginResponse.family_member.family_name || '',
        token: loginResponse.access_token,
        role: loginResponse.family_member.role
      }
      
      setAuth(userData, loginResponse.access_token)
      return { success: true }
    } catch (err: any) {
      console.error('注册失败:', err)
      const errorMessage = err.response?.data?.detail || '注册失败，请稍后重试'
      setError(errorMessage)
      return { success: false, error: errorMessage }
    } finally {
      setLoading(false)
    }
  }

  // 登录方法
  const login = async (loginData: LoginRequest) => {
    try {
      setLoading(true)
      clearError()
      
      const { loginApiV1AuthLoginPost } = getAuth()
      const response = await loginApiV1AuthLoginPost(loginData)
      
      const userData: User = {
        id: response.family_member.id.toString(),
        username: response.family_member.username,
        email: response.family_member.email,
        full_name: response.family_member.full_name,
        family_name: response.family_member.family_name || '',
        token: response.access_token,
        role: response.family_member.role
      }
      
      setAuth(userData, response.access_token)
      return { success: true }
    } catch (err: any) {
      console.error('登录失败:', err)
      const errorMessage = err.response?.data?.detail || '登录失败，请稍后重试'
      setError(errorMessage)
      return { success: false, error: errorMessage }
    } finally {
      setLoading(false)
    }
  }

  return {
    // 状态
    user,
    token,
    isLoading,
    error,
    isInitialized,
    
    // 计算属性
    isAuthenticated,
    userRole,
    
    // 方法
    setAuth,
    clearAuth,
    setLoading,
    setError,
    clearError,
    verifyToken,
    initializeAuth,
    register,
    login
  }
})
